'''
Created on Feb 27, 2012

@author: lino possamai
@license: GPLv3
'''
import pickle
import networkx as nx
from rules import get_rule_name
from rules import sel_group_in_probability
from rules import select_edge
from rules import aristocratic_original
from rules import init_aristocratic
from utility import load_pickled_data
from random import shuffle

def evolution_inertial_ari(filename, id_run, file_graph):
    
    g=load_pickled_data(file_graph)
    
    nnodi   = len(g.nodes())
    narchi  = len(g.edges())

    
    descrittori, GO, GO_incr = init_aristocratic(g,nnodi)
    
    fh = open("ari_edges_%d.txt" % (id_run,),"w")
    
    for i in range(0, narchi):
        index   = sel_group_in_probability(descrittori)
        e       = aristocratic_original(index,descrittori,GO_incr,GO,g)
        fh.write("%d %d\n" % (e[0],e[1]))

        if i % 1000 == 0 and i>0:
            print i
            fh.flush()
    fh.close()

def evolution_inertial(filename, tecnica, id_run, file_archi, file_graph):
    
    lista_archi={}
    #g_complete,archi,narchi, nnodi=load_pajek(filename, 2)
    
    g_complete=load_pickled_data(file_graph)
    archi=load_pickled_data(file_archi)
    
    nnodi=len(g_complete.nodes())
    narchi=len(archi)
    
    print "pajek file read."
    g=nx.Graph()
    g.add_nodes_from(range(1,nnodi+1))
    
    shuffle(archi)
    lista_archi[1]=set(archi)
    
    fh = open("%s_edges_%d.txt" % (get_rule_name(tecnica),id_run),"w")
    for i in range(0,narchi):
        
        index = sel_group_in_probability(lista_archi)
        e=select_edge(index, lista_archi, tecnica, g, g_complete)
        
        fh.write("%d %d\n" % (e[0],e[1]))
        
        if i % 100 == 0 and i>0:
            print i
            fh.flush()
    fh.close()

def evolution_inertial_rndwalk(filename, id_run, file_archi, file_graph):
    
    lista_archi={}
    
    g_complete=load_pickled_data(file_graph)
    archi=load_pickled_data(file_archi)
    
    nnodi=len(g_complete.nodes())
    narchi=len(archi)
    
    print "pajek file read."
    g=nx.Graph()
    g.add_nodes_from(range(1,nnodi+1))
    
    shuffle(archi)
    lista_archi[1]=set(archi)
    
    fh = open("%s_edges_%d.txt" % (get_rule_name(tecnica),id_run),"w")
    for i in range(0,narchi):
        
        index = sel_group_in_probability(lista_archi)
        e=select_edge(index, lista_archi, tecnica, g, g_complete)
        
        fh.write("%d %d\n" % (e[0],e[1]))
        
        if i % 100 == 0 and i>0:
            print i
            fh.flush()
    fh.close()
